//
//  OnlineUserViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/11.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "OnlineUserViewController.h"
#import "OnlineUserCell.h"
#import "OnlineUserInfo.h"
#import "MyInfoViewController.h"
#import "OnlineUserDetailViewController.h"

NSString const *OnlineUserViewControllerTitleParamKey = @"OnlineUserViewControllerTitleParamKey";

@interface OnlineUserViewController ()
{
    RSWDataOperation *_manager;
    
    NSMutableArray *_qdData;
}
@end

@implementation OnlineUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    NSString *title = self.param[OnlineUserViewControllerTitleParamKey];
    [self setBackNavigateItemTitle:title];
    
    [self initVariable];
    [self initUI];
    
    [self addMainThreadObserverWithDictionarySelector:@{CurrentUserCurrentUserHeadImageUpdateNotification:
                                                            @"observerCurrentUserCurrentUserHeadImageUpdateNotification:",XLGHeadImageDownloadQueueHeadImageDownloadResultNotification:
                                                            @"observerHeadImageDownloadQueueHeadImageDownloadResultNotification:"}];
    [self addKeyboardObserver];
    
    [_manager getOnlineUserListCompletion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [self requestComplete:nil funcationName:@"getOnlineUserListCompletion" result:nResult output:list error:error];
     }];
}

- (void)initVariable
{
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    _qdData = [NSMutableArray new];
}

- (void)initUI
{
    [self createTableView:XUITabelViewStyleTypePlain];
    _ctable.showsVerticalScrollIndicator = NO;
    _ctable.separatorExistFollowCell = YES;
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [_manager terminateRequest];
    [self removeObserver];
}

#pragma mark --
#pragma mark refresh tableView

-(void)requestComplete:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    _bRefreshing = NO ;
    
    if([szFuncationname isEqualToString:@"getOnlineUserListCompletion"])
    {
        [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
         {
             switch(requestResult)
             {
                 case YES:
                 {
                     _qdData = output;
                     
                     [_ctable reloadData];
                     
                     break;
                 }
                 default:
                 {
                     [UIAlertView showErrorMsg:@"数据请求失败"];
                     break;
                 }
             }
         }];
    } 
}

#pragma mark --
#pragma mark -- tableView delegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _qdData.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OnlineUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[OnlineUserCell alloc]initWithReuseIdentifier:@"cell"];
    }
    
    OnlineUserInfo *c = [_qdData objectAtIndex:indexPath.row];
    
    cell.szTag = [c.userNumber toNSString];
    cell.userName.text = c.userName;
    cell.mobilePhoe.text = c.mobilePhone;
    
    UIImage *headImage = nil;
    if(c.logoURL.length >0)
    {
        if([c.logoURL rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
        {
            XLGHeadImageCache *h = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:c.logoURL forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
            if(h != nil)
                headImage = h;
            else
                headImage = [UIImage imageNamed:@"img_defaulthead.png"];
        }
        else
        {
            NSString *h = [c.logoURL substringFromIndex:[c.logoURL rangeOfString:ServiceDefaultHeadImageTag].length];
            headImage = [UIImage imageNamed:h];
        }
    }
    else
        headImage = [UIImage imageNamed:@"img_defaulthead.png"];
    
    cell.logoUrl = headImage;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [UIViewController closeKeyBoard];
    
    OnlineUserInfo * c = [_qdData objectAtIndex:indexPath.row];
    
    if([c.userNumber isEqual:[MyInfo myInfo].userNumber] == NO)
    {
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        p.param[OnlineUserDetailViewControllerDetailInfoParamKey] = c;
        [XUINavigationController pushViewControllerClass:[OnlineUserDetailViewController class] withSwitchParam:p];
    }
    else
    {
        [XUINavigationController pushViewControllerClass:[MyInfoViewController class]];
    }
}

#pragma mark --
#pragma mark -- refresh headImage

-(void)observerHeadImageDownloadQueueHeadImageDownloadResultNotification:(NSNotification*)noti
{
    NSString *path =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultPathKey];
    NSString *URL =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultURLKey];
    
    for(OnlineUserInfo * c in _qdData)
    {
         if(c.logoURL.length >0 && [URL rangeOfString:c.logoURL].location != NSNotFound)
         {
             OnlineUserCell *cell = (OnlineUserCell *)[_ctable findVisibleCellWithTag:[c.userNumber toNSString]];
             if(cell != nil)
             {
                 XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue setCacheWithHeadImageURL:URL andHeadImagePath:path forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
                 
                 cell.logoUrl = cache;
             }
         }
     }
}

-(void)observerCurrentUserCurrentUserHeadImageUpdateNotification:(NSNotification*)noti
{
    [_manager getOnlineUserListCompletion:^(NSInteger nResult, NSArray *list, NSError *error)
     {
         [self requestComplete:nil funcationName:@"getOnlineUserListCompletion" result:nResult output:list error:error];
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
